package com.example.wenqujingdian.api;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.storage.StorageManager;
import android.text.TextUtils;
import android.util.Log;

import com.example.wenqujingdian.MyApplication;
import com.example.wenqujingdian.bean.FileBean;
import com.example.wenqujingdian.model.AudioClassBean;
import com.example.wenqujingdian.model.AudioLocalDetailBean;
import com.example.wenqujingdian.model.AudioLocalMoreBean;
import com.example.wenqujingdian.model.BookClassBean;
import com.example.wenqujingdian.model.LocalBookBean;
import com.example.wenqujingdian.model.LocalOrgBean;
import com.example.wenqujingdian.model.VideoHomeBean;
import com.example.wenqujingdian.model.VideoLocalDetailBean;
import com.example.wenqujingdian.model.VideoLocalListBean;
import com.example.wenqujingdian.utils.Lsetting;
import com.example.wenqujingdian.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import static android.provider.MediaStore.Video.Thumbnails.MINI_KIND;

/**
 * Create by kxliu on 2018/11/21
 */
public class JsonDataManager {

    private final static JsonDataManager INSTANCE = new JsonDataManager();

//    private JsonDataManager() {
////        this.mContext = context;
//    }

//    public String specificPath = getSpecificPath();

    public static JsonDataManager getInstance() {
        return INSTANCE;
    }

    private String getLocalJson(String fileName) {
        String specificPath = getSpecificPath();
        if (specificPath.length() != 0) {
            File specificFile = new File(specificPath);
            File[] wenqujingdianPackage = specificFile.listFiles();
            for (File file2 : wenqujingdianPackage) {
                if (file2.toString().contains(Contants.CONFIG)) {
                    File[] files2 = file2.listFiles();
                    for (File file3 : files2) {
                        if (file3.getName().equals(fileName)) {
                            String s1 = loadFromSDFile(file3);
                            return s1;
                        }
                    }
                }
            }
        }
        return "";
    }

    private String getLocalTxt() {
        String rootPath = getSDCardRootPath();
        if (TextUtils.isEmpty(rootPath)) return "";
        File specificFile = new File(rootPath);
        File[] packageFile = specificFile.listFiles();
        for (File file : packageFile) {
            if (file.isFile()) {
                if (file.getName().equals("notice.txt")) {
                    return loadFromSDTXT(file);
                }
            }
        }
        return "";
    }

    /**
     * 获取config文件路径
     *
     * @return
     */
    public String getConfigFilePath() {
        String specificPath = getSpecificPath();
        if (specificPath.length() != 0) {
            File specificFile = new File(specificPath);
            File[] wenqujingdianPackage = specificFile.listFiles();
            for (File file2 : wenqujingdianPackage) {
                if (file2.toString().contains(Contants.CONFIG)) {
                    return file2.getAbsolutePath();
                }
            }
        }
        return null;
    }


    public boolean checkFileExist() {
        String specificPath = getSpecificPath();
        if (specificPath.length() != 0) {
            File specificFile = new File(specificPath);
            File[] wenqujingdianPackage = specificFile.listFiles();
            for (File file2 : wenqujingdianPackage) {
                if (file2.toString().contains(Contants.CONFIG)) {
                    File[] files2 = file2.listFiles();
                    for (File file3 : files2) {
                        if (file3.toString().contains("booktype.json")) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    private String loadFromSDFile(File f) {
        String result = null;
        try {
            int length = (int) f.length();
            byte[] buff = new byte[length];
            FileInputStream fin = new FileInputStream(f);
            fin.read(buff);
            fin.close();
            result = new String(buff, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private String loadFromSDTXT(File f) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bf = null;
        try {
            FileInputStream fin = new FileInputStream(f);
            InputStreamReader isr = new InputStreamReader(fin, "UTF-8");
            bf = new BufferedReader(isr);
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bf != null) {
                    bf.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return stringBuilder.toString();


       /* String result = null;
        try {
            int length = (int) f.length();
            byte[] buff = new byte[length];
            FileInputStream fin = new FileInputStream(f);
            fin.read(buff);
            fin.close();
            result = new String(buff, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;*/
    }

    public String getSpecificPath() {
        if (Lsetting.debug) {
            return Environment.getExternalStorageDirectory()+"/Download/offline.wenqujingdian.com";
        }
        String externalStorageDirectory;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            externalStorageDirectory = getESPathForM(true);
            if (externalStorageDirectory != null) {
                return findFilePath(externalStorageDirectory, Contants.ROOTDIR);
            }
        } else {
            externalStorageDirectory = getExternalStorageDirectory();
            if (externalStorageDirectory.length() != 0 && externalStorageDirectory.contains("/")) {
                String[] split = externalStorageDirectory.split("/");
                String parentPath = "/" + split[1];
                File parent = new File(parentPath);
                if (parent.exists()) {
                    String specificPackage = getSpecificPackage(parent);
                    if (specificPackage.contains(Contants.ROOTDIR)) {
                        return specificPackage;
                    }
                }
            }
        }

        return "";
    }

    /**
     * 获取SD卡的根目录
     *
     * @return
     */
    public String getSDCardRootPath() {

        String externalStorageDirectory;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            externalStorageDirectory = getESPathForM(true);
            if (externalStorageDirectory != null) {
                return findFilePath(externalStorageDirectory, "notice");
            }
        } else {
            externalStorageDirectory = getExternalStorageDirectory();
            if (externalStorageDirectory.length() != 0 && externalStorageDirectory.contains("/")) {
                String[] split = externalStorageDirectory.split("/");
                String parentPath = "/" + split[1];
                File parent = new File(parentPath);
                if (parent.exists()) {
                    String specificPackage = getNoticeDir(parent);
                    if (specificPackage.contains("notice")) {
                        return specificPackage;
                    }
                }

            }
        }

        return "";
    }

    /**
     * 获取指定的文件目录
     *
     * @param SDCardPath 当前需要查找的父目录
     * @param rootDir    要查找的目录
     */
    private synchronized String findFilePath(String SDCardPath, String rootDir) {
        File f = new File(SDCardPath);
        if (f.exists() && f.isDirectory()) {
            File[] files = f.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        if (file.getName().equals(rootDir)) {
                            return file.getAbsolutePath();
                        }
                    }
                }
            }
        }
        return "";
    }

    private String getESPathForM(boolean is_removale) {

        StorageManager mStorageManager = (StorageManager) MyApplication.mContext.getSystemService(Context.STORAGE_SERVICE);
        Class<?> storageVolumeClazz = null;
        try {
            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
            Object result = getVolumeList.invoke(mStorageManager);
            final int length = Array.getLength(result);
            for (int i = 0; i < length; i++) {
                Object storageVolumeElement = Array.get(result, i);
                String path = (String) getPath.invoke(storageVolumeElement);
                boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
                if (is_removale == removable) {
                    return path;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return "";
    }

    private String getSpecificPackage(File file) {
        File[] files = file.listFiles();
        if (files != null) {
            for (File file1 : files) {
                if (file1.isDirectory()) {
                    if (file1.toString().contains("offline.wenqujingdian.com")) {
                        return file1.toString();
                    } else {
                        String specificPackage = getSpecificPackage(file1);
                        if (!specificPackage.equals("")) {
                            return specificPackage;
                        }
                    }
                }
            }
        }
        return "";
    }

    private String getNoticeDir(File file) {
        File[] files = file.listFiles();
        if (files != null) {
            for (File file1 : files) {
                if (file1.isDirectory()) {
                    if (file1.toString().contains("notice")) {
                        return file1.toString();
                    } else {
                        String specificPackage = getNoticeDir(file1);
                        if (!specificPackage.equals("")) {
                            return specificPackage;
                        }
                    }
                }
            }
        }
        return "";
    }

    private synchronized String getExternalStorageDirectory() {
        String dir = new String();
        try {
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            String line;
            BufferedReader br = new BufferedReader(isr);
            String s = br.toString();
            Log.d("butterReader", "allPath:" + s);
            while ((line = br.readLine()) != null) {
                if (line.contains("secure")) continue;
                if (line.contains("asec")) continue;

                if (line.contains("fat")) {
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
//                        dir = dir.concat(columns[1]);
                        dir = dir.concat("*" + columns[1] + "\n");

                        break;
                    }
                } else if (line.contains("fuse")) {
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
//                        dir = dir.concat(columns[1]);
                        dir = dir.concat(columns[1] + "\n");
                        break;
                    }
                }
                Log.i("外置SD卡路径", dir);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return dir;
    }

    /**
     * 解析
     *
     * @param json
     * @param cls
     * @param <T>
     * @return
     */
    public <T> T jsonToBean(String json, Class<T> cls) {
        Gson gson = new Gson();
        T data = gson.fromJson(json, cls);
        return data;
    }

    private <T> List<T> jsonToList(String json, Class<T> cls) {
        Gson gson = new Gson();
        List<T> list = new ArrayList<>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) {
            list.add(gson.fromJson(elem, cls));
        }
        return list;
    }

    public interface OnLocalDataListener<T> {
        void onSuccess(T data);

        void onFail(String info);
    }

    public interface OnLocalListDataListener<T> {
        void onSuccess(List<T> data);

        void onFail(String info);
    }

    public interface OnFileExistListener {
        void onSuccess(String exist);

        void onFail(String info);
    }

    /**
     * 获取机构信息
     *
     * @param name
     * @param listener
     */
    public void getOrgData(final String name, final Context context,
                           final OnLocalDataListener<LocalOrgBean> listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String localJson = getLocalJson(name);
//                    String localJson = BooksUtils.getJson(context, name);
                    if (localJson == null || localJson.equals("")) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onFail("未检测到SD卡以及外部存储设备");
                            }
                        });
                    } else {
                        final LocalOrgBean localOrgBean = jsonToBean(localJson, LocalOrgBean.class);
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (localOrgBean != null) {
                                    listener.onSuccess(localOrgBean);
                                } else {
                                    listener.onFail("未找到指定文件");
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("未检测到SD卡以及外部存储设备");
                        }
                    });
                }

            }
        }).start();
    }

    /**
     * 获取本地图书
     *
     * @param name
     * @param listener
     */
    public void getLocalBookData(final String name, final Context context,
                                 final OnLocalListDataListener<LocalBookBean> listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String localBookJson = getLocalJson(/*path,*/ name);
//                String localBookJson = BooksUtils.getJson(context,name);
                    if (localBookJson == null || localBookJson.equals("")) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onFail("未找到指定文件");
                                ToastUtil.show("未找到指定文件");
                            }
                        });
                    } else {
                        final List<LocalBookBean> localBookBeans = jsonToList(localBookJson, LocalBookBean.class);
                        if (localBookBeans != null && localBookBeans.size() > 0){
                            ListIterator<LocalBookBean> localBookBeanListIterator = localBookBeans.listIterator();
                            while (localBookBeanListIterator.hasNext()) {
                                LocalBookBean next = localBookBeanListIterator.next();
                                if (next.getBookId().equals("623")) {
                                    localBookBeans.remove(next);
                                    int e = Log.e("a", "a");
                                    break;

                                }
                            }
                        }
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (localBookBeans != null && localBookBeans.size() > 0) {
                                    listener.onSuccess(localBookBeans);
                                } else {
                                    listener.onFail("");
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("未检测到SD卡以及外部存储设备");
                        }
                    });
                }
            }
        }).start();
    }

    public void getBookClassData(final String name, final Context context,
                                 final OnLocalListDataListener<BookClassBean> listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String localClass = getLocalJson(/*path,*/ name);
//                String localClass = BooksUtils.getJson(context,name);
                    if (localClass == null || localClass.equals("")) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onFail("未检测到SD卡以及外部存储设备");
                            }
                        });
                    } else {
                        final List<BookClassBean> localBookBeans = jsonToList(localClass, BookClassBean.class);
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (localBookBeans != null && localBookBeans.size() > 0) {
                                    listener.onSuccess(localBookBeans);
                                } else {
                                    listener.onFail("未找到指定文件");
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("未检测到SD卡以及外部存储设备");
                        }
                    });
                }
            }
        }).start();
    }

    public void getSettingData(final String name, final OnLocalDataListener<String> listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final String settingJson = getLocalJson(name);
//                final String settingJson = BooksUtils.getJson(context,name);
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            if (!settingJson.equals("") && settingJson != null) {
                                listener.onSuccess(settingJson);
                            } else {
                                listener.onFail("未检测到SD卡以及外部存储设备");
                            }
                        }
                    });
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("未检测到SD卡以及外部存储设备");
                        }
                    });
                }

            }
        }).start();
    }

    public void getVideoClassData(final String name, final Context context,
                                  final OnLocalDataListener<VideoHomeBean> listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String videoClassJson = getLocalJson(/*path,*/ name);
//                    String videoClassJson = BooksUtils.getJson(context, name);
                    if (null == videoClassJson || videoClassJson.equals("")) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onFail("未检测到SD卡以及外部存储设备");
                            }
                        });
                    } else {
                        final VideoHomeBean videoHomeBean = jsonToBean(videoClassJson, VideoHomeBean.class);
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (videoHomeBean != null) {
                                    listener.onSuccess(videoHomeBean);
                                } else {
                                    listener.onFail("未找到指定文件");
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("未检测到SD卡以及外部存储设备");
                        }
                    });
                }
            }
        }).start();
    }

    public void getLocalVideoClassList(final String name, final Context context,
                                       final OnLocalListDataListener<VideoLocalListBean> listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String localVideoClassJson = getLocalJson(/*path,*/ name);
//                    String localVideoClassJson = BooksUtils.getJson(context, name);
                    if (localVideoClassJson == null || localVideoClassJson.equals("")) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onFail("未检测到SD卡以及外部存储设备");
                            }
                        });
                    } else {
                        final List<VideoLocalListBean> videoLocalListBeans = jsonToList(localVideoClassJson, VideoLocalListBean.class);
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (videoLocalListBeans != null && videoLocalListBeans.size() > 0) {
                                    listener.onSuccess(videoLocalListBeans);
                                } else {
                                    listener.onFail("未找到指定文件");
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("未检测到SD卡以及外部存储设备");
                        }
                    });
                }
            }
        }).start();
    }

    public void getVideoChildList(final Context context, final String name,
                                  final OnLocalListDataListener<VideoLocalDetailBean> listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String json = getLocalJson(name);
//                    String json = BooksUtils.getJson(context, name);
                    if (json == null || json.equals("")) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onFail("未检测到SD卡以及外部存储设备");
                            }
                        });
                    } else {
                        final List<VideoLocalDetailBean> videoLocalDetailBeans = jsonToList(json, VideoLocalDetailBean.class);
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (videoLocalDetailBeans != null && videoLocalDetailBeans.size() > 0) {
                                    listener.onSuccess(videoLocalDetailBeans);
                                } else {
                                    listener.onFail("未找到指定文件");
                                }
                            }
                        });

                    }
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("未检测到SD卡以及外部存储设备");
                        }
                    });
                }
            }
        }).start();
    }

    public void getAudioClassData(final Context context, final String name,
                                  final OnLocalDataListener<AudioClassBean> listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String audioClassJson = getLocalJson(/*path,*/ name);
//                    String audioClassJson = BooksUtils.getJson(context, name);
                    if (null == audioClassJson || audioClassJson.equals("")) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onFail("未检测到SD卡以及外部存储设备");
                            }
                        });
                    } else {
                        final AudioClassBean audioClassBean = jsonToBean(audioClassJson, AudioClassBean.class);
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (audioClassBean != null) {
                                    listener.onSuccess(audioClassBean);
                                } else {
                                    listener.onFail("未找到指定文件");
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("未检测到SD卡以及外部存储设备");
                        }
                    });
                }
            }
        }).start();
    }

    public void getAudioDetailData(final Context context, final String name,
                                   final OnLocalListDataListener<AudioLocalDetailBean> listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String json = getLocalJson(name);
//                    String json = BooksUtils.getJson(context, name);
                    if (json == null || json.equals("")) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onFail("未检测到SD卡以及外部存储设备");
                            }
                        });
                    } else {
                        final List<AudioLocalDetailBean> audioLocalDetailBeans = jsonToList(json, AudioLocalDetailBean.class);
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (audioLocalDetailBeans != null && audioLocalDetailBeans.size() > 0) {
                                    listener.onSuccess(audioLocalDetailBeans);
                                } else {
                                    listener.onFail("未找到指定文件");
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("未检测到SD卡以及外部存储设备");
                        }
                    });
                }
            }
        }).start();
    }

    public void getLocalAudioList(final String name, final Context context,
                                  final OnLocalListDataListener<AudioLocalMoreBean> listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String localVideoClassJson = getLocalJson(/*path,*/ name);
//                    String localVideoClassJson = BooksUtils.getJson(context, name);
                    if (localVideoClassJson == null || localVideoClassJson.equals("")) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onFail("未检测到SD卡以及外部存储设备");
                            }
                        });
                    } else {
                        final List<AudioLocalMoreBean> videoLocalListBeans = jsonToList(localVideoClassJson, AudioLocalMoreBean.class);
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (videoLocalListBeans != null && videoLocalListBeans.size() > 0) {
                                    listener.onSuccess(videoLocalListBeans);
                                } else {
                                    listener.onFail("未找到指定文件");
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("未检测到SD卡以及外部存储设备");
                        }
                    });
                }
            }
        }).start();
    }


    public void createBookTypeFile(final String configFilePath, final String imei) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = new File(configFilePath, "booktype.json");
                    FileOutputStream stream = new FileOutputStream(file);
                    String content = "{name:" + imei + "}";
                    stream.write(content.getBytes());
                    stream.close();
                } catch (Exception e) {

                }
            }
        }).start();
    }

    public void getBookTypeFile(final OnFileExistListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final String bookType = getLocalJson("booktype.json");
                    if (!bookType.equals("") || bookType != null) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject object = new JSONObject(bookType);
                                    String name = object.getString("name");
                                    listener.onSuccess(name);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        });

                    }
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("无效的SD卡，请联系管理员");
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 获取本地存放的通知内容
     *
     * @param listener
     */
    public void getNoticeContent(final OnFileExistListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
//                    final String bookType = BooksUtils.getNoticeText(name);
                    final String bookType = getLocalTxt();
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                listener.onSuccess(bookType);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("无效的SD卡，请联系管理员");
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 获取风采展示的分类内容
     *
     * @param listener
     */
    public void getCustomerDate(final String fileName, final int fileType, final OnLocalListDataListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final List<FileBean> list = getCustomerData(fileName,fileType);
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                listener.onSuccess(list);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("未获取到数据，请检查SD卡");
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 获取用户风采数据
     *
     * @param fileName 文件夹名称
     * @param type     （0.图片，1.视频 2.文档）
     * @return
     */
    private List<FileBean> getCustomerData(String fileName, int type) {
        String specificPath = getSpecificPath();
//        String specificPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/offline.wenqujingdian.com";
        if (TextUtils.isEmpty(specificPath)) return null;
        File specificFile = new File(specificPath);
        File[] wenqujingdianPackage = specificFile.listFiles();
        List<FileBean> list = new ArrayList<>();
        for (File file2 : wenqujingdianPackage) {
            if (file2.toString().contains(fileName)) {
                File[] files2 = file2.listFiles();
                for (File file3 : files2) {
                    String path = file3.getAbsolutePath();
                    String name = file3.getName();
                    if (type == 0 && (path.endsWith(".jpg")  || path.endsWith(".png") || path.endsWith(".jpeg"))) {
                        FileBean fileBean = new FileBean();
                        fileBean.setFileName(name);
                        fileBean.setFilePath(path);
                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                        Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, 150, 150);
                        fileBean.setBitmap(thumbnail);
                        list.add(fileBean);
                    }else if (type == 1 && (name.endsWith(".mp4")||name.endsWith(".3gp")
                            ||name.endsWith(".avi")||name.endsWith(".flv")||name.endsWith(".rmvb")||name.endsWith(".mkv"))){
                        FileBean fileBean = new FileBean();
                        fileBean.setFileName(name);
                        fileBean.setFilePath(path);
                        Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(path,MINI_KIND);
                        fileBean.setBitmap(thumbnail);
                        list.add(fileBean);
                    }else if (type == 2 && (name.endsWith(".txt") || name.endsWith(".pdf"))){
                        FileBean fileBean = new FileBean();
                        fileBean.setFileName(name);
                        fileBean.setFilePath(path);
                        list.add(fileBean);
                    }

                }
            }
        }
        return list;
    }


    /**
     * 获取本地图书
     *
     * @param name
     * @param listener
     */
    public void getLocalBookData2(final String name, final Context context,
                                 final OnLocalListDataListener<LocalBookBean> listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //将json数据变成字符串
                    StringBuilder stringBuilder = new StringBuilder();
                    try {
                        //获取assets资源管理器
                        AssetManager assetManager = context.getAssets();
                        //通过管理器打开文件并读取
                        BufferedReader bf = new BufferedReader(new InputStreamReader(
                                assetManager.open(name)));
                        String line;
                        while ((line = bf.readLine()) != null) {
                            stringBuilder.append(line);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String localBookJson = stringBuilder.toString();
//                String localBookJson = BooksUtils.getJson(context,name);
                    if (localBookJson == null || localBookJson.equals("")) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onFail("未找到指定文件");
                                ToastUtil.show("未找到指定文件");
                            }
                        });
                    } else {
                        final List<LocalBookBean> localBookBeans = jsonToList(localBookJson, LocalBookBean.class);
                        if (localBookBeans != null && localBookBeans.size() > 0){
                            ListIterator<LocalBookBean> localBookBeanListIterator = localBookBeans.listIterator();
                            while (localBookBeanListIterator.hasNext()) {
                                LocalBookBean next = localBookBeanListIterator.next();
                                if (next.getBookId().equals("623")) {
                                    localBookBeans.remove(next);
                                    int e = Log.e("a", "a");
                                    break;

                                }
                            }
                        }
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (localBookBeans != null && localBookBeans.size() > 0) {
                                    listener.onSuccess(localBookBeans);
                                } else {
                                    listener.onFail("");
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onFail("未检测到SD卡以及外部存储设备");
                        }
                    });
                }
            }
        }).start();
    }
}
